<template>
  <div>
    <el-card style="width: 500px;">
      <el-form label-width="80px" size="small">
        <!-- 头像上传 -->
        <el-upload
            class="avatar-uploader"
            :action="'http://' + sharedFilesModuleServerSocket + '/shared/files/upload'"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            accept="image/*"
        >
          <!-- 显示头像 -->
          <img v-if="form.avatarUrl" :src="form.avatarUrl" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>

        <!-- 用户名 -->
        <el-form-item label="用户名">
          <el-input v-model="form.username" disabled autocomplete="off"></el-input>
        </el-form-item>

        <!-- 昵称 -->
        <el-form-item label="昵称">
          <el-input v-model="form.nickname" autocomplete="off"></el-input>
        </el-form-item>

        <!-- 电话 -->
        <el-form-item label="电话">
          <el-input v-model="form.phone" autocomplete="off"></el-input>
        </el-form-item>

        <!-- 性别 -->
        <el-form-item label="性别">
          <el-select v-model="form.sex" placeholder="请选择性别" autocomplete="off">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
            <el-option label="其他" value="其他"></el-option>
          </el-select>
        </el-form-item>

        <!-- 角色 -->
        <el-form-item label="角色">
          <el-input v-model="form.role" disabled autocomplete="off"></el-input>
        </el-form-item>

        <!-- 保存按钮 -->
        <el-form-item>
          <el-button type="primary" @click="save">确 定</el-button>
        </el-form-item>
      </el-form>

      <el-form label-width="80px" size="small">
        <el-form-item label="账户余额">
          <el-input v-model="form.balance" disabled autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleRecharge">充 值</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-dialog title="账户充值" :visible.sync="dialogRechargeVisible" width="30%" >
      <el-form label-width="80px" size="small">
        <el-form-item label="充值数额">
          <el-input v-model="amount" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogRechargeVisible = false">取 消</el-button>
        <el-button type="primary" @click="recharge">确 定 充 值</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { sharedFilesModuleServerSocket } from "../../public/config";

export default {
  name: "Own",
  data() {
    return {
      sharedFilesModuleServerSocket: sharedFilesModuleServerSocket,
      form: {},
      individual: localStorage.getItem("individual") ? JSON.parse(localStorage.getItem("individual")) : {},
      dialogRechargeVisible: false,
      amount :0,
    };
  },
  created() {
    this.getIndividual().then(res => {
      console.log(res);
      this.form = res;
    });
  },
  methods: {
    // 获取用户信息
    async getIndividual() {
      return (await this.request.get("http://127.0.0.1:8094/merchant/individual/username/" + this.individual.username)).data;
    },

    // 保存用户信息
    save() {
      this.request.post("/merchant/individual/modify", this.form).then(response => {
        if (response.code === '200') {
          this.$message.success("保存成功");
          this.$emit("refreshUser");

          // 更新浏览器存储的用户信息
          this.getIndividual().then(res => {
            res.token = JSON.parse(localStorage.getItem("individual")).token;
            localStorage.setItem("individual", JSON.stringify(res));
          });
        } else {
          this.$message.error("保存失败");
        }
      });
    },

    // 获取头像的 URL
    getAvatarUrl(avatarId) {
      this.request.get("/shared/files/url/" + avatarId, { responseType: 'text' })
          .then(res => {
            this.form.avatarUrl = res.data; // 保存获取到的头像 URL
          })
          .catch(error => {
            console.error('获取头像 URL 失败:', error);
          });
    },

    // 上传成功后的处理
    handleAvatarSuccess(response) {
      this.form.avatarId = response; // 假设后端返回的是 avatarId
      this.getAvatarUrl(response); // 获取对应的头像 URL 并更新到 form.avatarUrl
    },

    // 上传前的文件验证
    beforeAvatarUpload(file) {
      const isAllowedType = file.type === 'image/png' || file.type === 'image/jpeg';
      const isLt100M = file.size / 1024 / 1024 < 100; // 限制文件大小

      if (!isAllowedType) {
        this.$message.error('上传文件必须是PNG或JPG格式。');
        return false;
      }
      if (!isLt100M) {
        this.$message.error('上传的图片大小不能超过 100MB。');
        return false;
      }
      return true;
    },

    handleRecharge() {
      this.dialogRechargeVisible = true;
      this.amount = 0;
    },

    recharge(){
      this.request.get("/merchant/individual/recharge" ,{
        params: {
          amount : this.amount
        }
      }).then(response => {
        if (response.code === '200') {
          this.dialogRechargeVisible = false;
          this.$message.success("充值成功");
          this.$emit("refreshUser");
          this.getIndividual().then(res => {
            res.token = JSON.parse(localStorage.getItem("individual")).token;
            localStorage.setItem("individual", JSON.stringify(res));
            this.form.balance = res.balance
          });
        } else {
          this.$message.error("充值失败");
        }
      });
    }

  }
};
</script>

<style scoped>
.avatar-uploader {
  text-align: center;
  padding-bottom: 10px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 138px;
  height: 138px;
  line-height: 138px;
  text-align: center;
}
.avatar {
  width: 138px;
  height: 138px;
  display: block;
}
</style>
